package com.fingard.dsp.bank.directbank.hbb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;

/**
 * @author Parker on 2019-08-13.
 * @version 1.0
 */
public class HBB01Base extends DirectBase {
    protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    protected static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";

    protected static TransIDHelper idHelper = new TransIDHelper(1,9999);

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter, HBB01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.serviceId)) {
            throw new Exception("未赋值serviceId");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("ebank");
        xmlWriter.writeStartElement("head");
        xmlWriter.writeElementString("serviceId", p_bankHeader.serviceId);
        xmlWriter.writeElementString("customerId", bankFront.org);
        xmlWriter.writeElementString("userId", bankFront.operator);
        xmlWriter.writeElementString("reqTime", Format.DateTime14Format.format(new Date()));
        xmlWriter.writeElementString("serialNo", p_bankHeader.serialNo);
        xmlWriter.writeEndElement();
    }


    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */
    protected String[] sendToBank(String p_reqStr) throws Exception {
        String[] retStr = new String[]{"", ""};
        String tmpUrl = bankFront.serverURL;
        WriteBankLogLn("1.提交银行的地址：" + tmpUrl);
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Method", "POST");
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        tmpWebRequest.setRequestProperty("connection", "close");//设置连接状态
        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    //进行签名
    protected String signature(String data) throws Exception {
        String signURL = bankFront.signURL;
        WriteBankLogLn("1.银行签名地址：" + signURL);
        WriteBankLogStep2(data);
        String signedData = "";
        WebRequest tmpWebRequest = new WebRequest(signURL);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Length", String.valueOf(data.length()));
        tmpWebRequest.setRequestProperty("Content-Type", "INFOSEC_SIGN/1.0");
        String charsetName = getCharset();
        byte[] tmpToWriteBytes = data.getBytes(charsetName);
        String[] retSign = tmpWebRequest.upload(tmpToWriteBytes,"GBK");

        if (retSign[0].length() == 0) {
            try {
                WriteBankLogLn("3.签名返回的结果：" + retSign[1]);
                XmlTextReader tmpXmlReader = new XmlTextReader(retSign[1]);
                String tmpRest = tmpXmlReader.getSimpleText("result");
                if ("0".equals(tmpRest)) {
                    WriteBankLogLn("签名成功");
                    signedData = tmpXmlReader.getSimpleText("sign");
                } else {
                    WriteBankLogLn("签名失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                WriteBankLogLn(e.getMessage());
            }
        } else {
            WriteBankLogLn("与银行签名端口通讯失败；详细信息：" + retSign[1]);
        }
        return signedData;
    }

    protected String getSingData(XmlTextWriter xmlWriter) throws Exception {
        String singData = xmlWriter.toXmlString();
        return signature(singData.substring(singData.indexOf("<head>")));
    }

    protected String getQryTransID(){
        return Format.DateTime12Year2Format.format(new Date())+idHelper.getNextIDStr();
    }
}
